package com.dminvoicemanager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.dminvoicemanager.tabs.DM_Retailer_Info_Main_Tabs;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class DM_ProductiveCalls extends Activity {

	private String DBNAME = "dminvoicemanager.db";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String INV_COMPANY_BRANCH = "FCompanyBranch";
	private String ITEM_CONTROL = "fControl";
	private String USER_SETTINGS = "usersettings";
	private String ITEM_DEBTOR = "fDebtor";
	private String INV_DETAILS = "FinvHed";
	private String DAILY_NONE_PRDCALLS_HEAD = "fNonePrd";

	final private static int DIALOG_SAVE_STOCK_LOADING = 1;
	final private static int DIALOG_CANCEL_STOCK_LOADING = 2;
	final private static int DIALOG_UNDO_STOCK_LOADING = 3;
	final private static int DIALOG_PRINT_STOCK_LOADING = 4;

	AlertDialog StockLoadingAlert = null;

	EditText etdmstloadingdate;

	Button etdmstloadingrefno, btdmstLoadingselectitem, btBack, btUpdate;

	String StlTransTypePrefix, strLatestAdjustSerial, currentUserStLoad,
			retailerCode, stlAgentPrefixType, currentUserTemp, UserLocCode,
			txtDate, strLatest, currentUserPrefix, newAdjustmenrRefNoCode,
			currentUserPrefixLoad, UserRouteCode, strlastId, TxndateRefno,
			strLatestRef, strTagUpdate;
	String match = "5";

	String TagId, currentAdjustRefCode, invDetLastRefNo;

	int invDetLastSequence = 1;

	private SQLiteDatabase mydb;

	public void btnBack(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_InvoiceMenu.class);
		myIntent.putExtra("TAGID", "SALES");
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivityForResult(myIntent, 0);
		finish();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_daily_none_prod_calls);

		Bundle bundle = getIntent().getExtras();
		TagId = bundle.getString("TAGID");
		etdmstloadingdate = (EditText) findViewById(R.id.etdmstloadingdate);
		etdmstloadingdate.setText(getCurrentTimeString());
		etdmstloadingrefno = (Button) findViewById(R.id.etdmstloadingrefno);
		btdmstLoadingselectitem = (Button) findViewById(R.id.btdmstLoadingselectitem);
		btBack = (Button) findViewById(R.id.BtnBack);
		btUpdate = (Button) findViewById(R.id.BtnUpdate);

		stLoadingAgentPrefix();// Check Current Agent Prefix
		stLoadingTransType();// Check Current Trans Type
		currentUserStLoadChk();
		checkLatestAdjustmentSerial();
		currentuserTemp();
		// createNewAdjustmentAddition();
		btBack.setEnabled(true);

		btdmstLoadingselectitem.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				// RefreshList();
				AutoIncrementRefNo();
				// createNewAdjustmentAddition();
				btUpdate.setEnabled(true);
				// btBack.setEnabled(false);

				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_ProductiveCalls.this).create();
				// Setting Dialog Title
				alertDialog.setTitle("Validating  Update");
				// Setting Dialog Message
				alertDialog.setMessage("Click Update Button to Continue...");
				// Setting Icon to Dialog
				alertDialog.setIcon(R.drawable.warning);
				// Setting OK Button
				alertDialog.setButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {

								alertDialog.dismiss();
							}
						});
				// Showing Alert Message
				alertDialog.show();
				alertDialog.setCanceledOnTouchOutside(false);
				// return;
			}

		});

		btUpdate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				btBack.setEnabled(true);

				if (etdmstloadingrefno.length() == 0) {

					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_ProductiveCalls.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("Validating RefNo Reading");
					// Setting Dialog Message
					alertDialog
							.setMessage("Reference No Cannot Be Empty Click Refresh Button to Update...");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {

									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
					alertDialog.setCanceledOnTouchOutside(false);
					return;
				} else {
					populateStockLoadList();
				}
			}

		});

		btBack.setOnClickListener(new View.OnClickListener() {
			//
			public void onClick(View view) {
				// Intent myIntent = new Intent(view.getContext(),
				// DM_InvoiceMenu.class);
				// myIntent.putExtra("TAGID", "5");
				// myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				// | Intent.FLAG_ACTIVITY_NEW_TASK);
				// startActivityForResult(myIntent, 0);
				// finish();
				// DeleteAll();
				// Log.v("", "DeleteAll");
			}
			//
			//
		});

		// if(TagId.equals("3"))
		// {
		// //RefreshList();
		// RefreshNew();
		// btUpdate.setEnabled(true);
		// Log.v("", "TagID / TagID -::" + TagId + ":"+ TagId);
		// }

	}

	// Delete All From Table

	public void DeleteAll() {

		// ------------deleting Part---------------------//
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		String CurrentRefNo = etdmstloadingrefno.getText().toString();
		Cursor saveStLoadinghedDel = null;
		try {
			saveStLoadinghedDel = mydb.query(DAILY_NONE_PRDCALLS_HEAD, null,
					null, null, null, null, null);
			Log.v("",
					"Delete All Records:Status"
							+ saveStLoadinghedDel.getCount());
		} catch (Exception e) {
		}

		if (saveStLoadinghedDel != null) {
			if (saveStLoadinghedDel.getCount() > 0) {
				while (saveStLoadinghedDel.moveToNext()) {
					// String tempRepStLoadrefcode = saveStLoadinghedDel
					// .getString(1);
					Log.v("", "Delete All Records:Status");
					mydb.delete(DAILY_NONE_PRDCALLS_HEAD, null, null);
				}
			}
		}
		saveStLoadinghedDel.close();
		mydb.close();
	}

	// populate Vistdetail LoadList

	protected void populateStockLoadList() {
		// TODO Auto-generated method stub
		SimpleAdapter adaptertrdes = null;
		ListView lvtypedes = (ListView) findViewById(R.id.dmstockloadingdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colstloaddes_1", "colstloaddes_2",
				"colstloaddes_3", "colstloaddes_4" };
		int[] totrdes = new int[] { R.id.stloaditemrefdet,
				R.id.stloadcasevalue, R.id.stloadpiecevalue,
				R.id.btnstloaditemrefdet };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null; // debtor list
		Cursor allrowitemsdes2 = null; // invoice list
		Cursor allrowitemsdesNone = null; // none prd list
		Cursor getCurrentRecDet = null;
		// Cursor saveStLoadinghedCur = null;

		try {
			String DebcodeStr = "SELECT RD.RouteCode," + "RD.DebCode,"
					+ "FD.DebName," + "FD.OutDis"
					+ " FROM fRouteDet RD,fDebtor FD "
					+ "Where FD.DebCode = RD.DebCode AND RD.RouteCode ='"
					+ UserRouteCode + "'";
			allrowitemsdes = mydb.rawQuery(DebcodeStr, null);

		} catch (Exception e) {
			// handle the exception here
			// for example close the database connections etc..
		}

		int tag = 0;
		String Status = "";
		String DebName = "";
		String DebCode = "";
		String sWhereCondition = null;
		String rawitemsdet = "";
		boolean bInvoiceFound = false;
		boolean bReasonFound = false;
		boolean bNonProdCallHeadFound = false;

		txtDate = getCurrentTimeString().toString();
		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					bInvoiceFound = false;
					bReasonFound = false;
					bNonProdCallHeadFound = false;
					Status = null;
					rawitemsdet = null;
					DebCode = allrowitemsdes.getString(1);
					DebName = allrowitemsdes.getString(2);

					try {
						sWhereCondition = "TXNDATE='" + txtDate
								+ "' AND DEBCODE = '" + DebCode + "'";
						getCurrentRecDet = mydb.query(DAILY_NONE_PRDCALLS_HEAD,
								null, sWhereCondition, null, null, null, null);

						sWhereCondition = "TXNDATE='" + txtDate
								+ "' AND DEBCODE = '" + DebCode + "'";
						allrowitemsdes2 = mydb.query(INV_DETAILS,
								new String[] { "1" }, sWhereCondition, null,
								null, null, null);

						if (getCurrentRecDet != null) {
							if (getCurrentRecDet.getCount() > 0) {
								while (getCurrentRecDet.moveToNext()) {
									bNonProdCallHeadFound = true;
									Status = getCurrentRecDet.getString(5);
									Log.v("",
											"111 bNonProdCallHeadFound TRUE :Status"
													+ Status);
								}
							}
						}

						if (allrowitemsdes2 != null) {
							if (allrowitemsdes2.getCount() > 0) {
								bInvoiceFound = true;
								Log.v("", "222 bInvoiceFound TRUE :Status"
										+ Status);
							}
						}

					} catch (Exception e) {
						// handle the exception here
						// for example close the database connections etc..
						Log.v("", "333 Exception Status" + Status);
					}

					if (bNonProdCallHeadFound) {
						// *************
						// update check
						// *************
						if (bInvoiceFound) {
							Status = "V";
							Log.v("", "444 bInvoiceFound TRUE :Status" + Status);
						} else {
							try {
								sWhereCondition = "TXNDATE='" + txtDate
										+ "' AND DEBCODE = '" + DebCode
										+ "' AND UPPER(Status) = 'NP'";
								allrowitemsdesNone = mydb
										.query(DAILY_NONE_PRDCALLS_HEAD, null,
												sWhereCondition, null, null,
												null, null);

								if (allrowitemsdesNone != null) {
									if (allrowitemsdesNone.getCount() > 0) {
										while (allrowitemsdesNone.moveToNext()) {
											bReasonFound = true;
											Status = allrowitemsdesNone
													.getString(5);
											Log.v("",
													"555 bReasonFound TRUE :Status"
															+ Status);
										}
									}
								}

							} catch (Exception e) {
								// handle the exception here
								// for example close the database connections
								// etc..
								Log.v("", "666 Exception :Status" + Status);
							}

							// rawitemsdet = DebName + "/" + Status;
						}

						// if invoice or reason found then update the record
						// with new Status else do nothing
						if (bInvoiceFound || bReasonFound) {
							ContentValues newitemdetailrecord = new ContentValues();
							newitemdetailrecord.put("Status", Status);

							sWhereCondition = "TXNDATE='" + txtDate
									+ "' AND DEBCODE = '" + DebCode + "'";
							mydb.update(DAILY_NONE_PRDCALLS_HEAD,
									newitemdetailrecord, sWhereCondition, null);

							Log.v("",
									"777 bReasonFound and bReasonFound TRUE :Status"
											+ Status);

							final AlertDialog alertDialog = new AlertDialog.Builder(
									DM_ProductiveCalls.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("UPDATE");
							// Setting Dialog Message
							alertDialog
									.setMessage("Record Updated Successfully");
							// Setting Icon to Dialog
							alertDialog.setIcon(R.drawable.warning);
							// Setting OK Button
							alertDialog.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											alertDialog.dismiss();

										}
									});
						}

					} else {

						// *************
						// insert check
						// *************
						if (bInvoiceFound) {
							Status = "V";
							Log.v("", "888 bInvoiceFound  TRUE :Status"
									+ Status);
						} else {
							Status = "NV";
							Log.v("", "999 bInvoiceFound FALSE :Status"
									+ Status);
						}

						rawitemsdet = DebName + "/" + Status;

						ContentValues newStockLoadRecDetail = new ContentValues();

						newStockLoadRecDetail.put("RefNo", etdmstloadingrefno
								.getText().toString());
						newStockLoadRecDetail.put("TxnDate", etdmstloadingdate
								.getText().toString());
						newStockLoadRecDetail.put("DebCode", DebCode);
						newStockLoadRecDetail.put("DebName", DebName);
						newStockLoadRecDetail.put("Status", Status);
						newStockLoadRecDetail.put("Reason", "");
						newStockLoadRecDetail.put("stldmhedSync", "0");

						mydb.insert(DAILY_NONE_PRDCALLS_HEAD, null,
								newStockLoadRecDetail);

						Log.v("", "1010   :Status" + Status);

						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_ProductiveCalls.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("UPDATE");
						// Setting Dialog Message
						alertDialog.setMessage("Update Record Successfully");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();

									}
								});
					}

					Log.v("", "*****  FINAL  :Status" + Status + " DEBNAME :"
							+ DebName);

					rawitemsdet = DebName + "/" + Status;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colstloaddes_1", DebName);
					maptrdes.put("colstloaddes_2", "");
					maptrdes.put("colstloaddes_3", Status);
					maptrdes.put("colstloaddes_4", rawitemsdet);
					fillMapstrdes.add(maptrdes);

					Log.v("", "Outer2 / Outer2 -::" + rawitemsdet + ":"
							+ rawitemsdet);
				}
				// fill in the grid_item layout
				adaptertrdes = new SimpleAdapter(this, fillMapstrdes,
						R.layout.dm_daily_loading_list_raw, fromtrdes, totrdes);

				lvtypedes.setAdapter(adaptertrdes);
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_ProductiveCalls.this).create();
			}

		}

		final AlertDialog alertDialog = new AlertDialog.Builder(
				DM_ProductiveCalls.this).create();
		// Setting Dialog Title
		alertDialog.setTitle("UPDATE");
		// Setting Dialog Message
		alertDialog.setMessage("Update Record Successfully..");
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.warning);
		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				alertDialog.dismiss();

			}
		});
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);

		if (!allrowitemsdes.isClosed()) {
			allrowitemsdes.close();
		}
		if (!allrowitemsdes2.isClosed()) {
			allrowitemsdes2.close();
		}
		if (!getCurrentRecDet.isClosed()) {
			getCurrentRecDet.close();
		}

		if (allrowitemsdesNone != null && !allrowitemsdesNone.isClosed()) {
			allrowitemsdesNone.close();
		}

		if (mydb.isOpen()) {
			mydb.close();
		}

		// RefreshNew();
	}

	// Visit List when From Loading
	private void RefreshList() {

		// TODO Auto-generated method stub
		SimpleAdapter adaptertrdes = null;
		ListView lvtypedes = (ListView) findViewById(R.id.dmstockloadingdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colstloaddes_1", "colstloaddes_2",
				"colstloaddes_3", "colstloaddes_4" };
		int[] totrdes = new int[] { R.id.stloaditemrefdet,
				R.id.stloadcasevalue, R.id.stloadpiecevalue,
				R.id.btnstloaditemrefdet };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null; // debtor
		Cursor allrowitemsdes2 = null; // invoice list

		try {
			String DebcodeStr = "SELECT RD.RouteCode,RD.DebCode,FD.DebName,FD.OutDis FROM fRouteDet RD,fDebtor FD Where FD.DebCode = RD.DebCode AND RD.RouteCode ='"
					+ UserRouteCode + "'";
			allrowitemsdes = mydb.rawQuery(DebcodeStr, null);

		} catch (Exception e) {
		}

		String Status = "";
		String DebName = "";
		int tag = 0;
		String rawitemsdet = "";
		txtDate = getCurrentTimeString().toString();
		Log.v("", "Date / Date -::" + txtDate + ":" + txtDate);

		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {

					String DebCode = allrowitemsdes.getString(1);
					DebName = allrowitemsdes.getString(2);

					allrowitemsdes2 = mydb.query(INV_DETAILS, null, "txndate='"
							+ txtDate + "'", null, null, null, null);

					if (allrowitemsdes2.getCount() == 0) {
						DebName = allrowitemsdes.getString(2);
						Status = "NV";
					}

					if (allrowitemsdes2 != null) {
						if (allrowitemsdes2.getCount() > 0) {
							while (allrowitemsdes2.moveToNext()) {

								String DebCode2 = allrowitemsdes2.getString(10);

								if (DebCode.equals(DebCode2)) {
									Status = "V";
									DebName = allrowitemsdes.getString(2);
									tag = 1;
									break;
								} else {
									Status = "NV";
									DebName = allrowitemsdes.getString(2);
									tag = 1;
								}

								rawitemsdet = DebName + "/" + Status;

							}

						}

					}
					rawitemsdet = DebName + "/" + Status;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colstloaddes_1", DebName);
					maptrdes.put("colstloaddes_2", "");
					maptrdes.put("colstloaddes_3", Status);
					maptrdes.put("colstloaddes_4", rawitemsdet);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				adaptertrdes = new SimpleAdapter(this, fillMapstrdes,
						R.layout.dm_daily_loading_list_raw, fromtrdes, totrdes);

				lvtypedes.setAdapter(adaptertrdes);
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_ProductiveCalls.this).create();

			}

		}
		allrowitemsdes.close();
		allrowitemsdes2.close();
		mydb.close();

	}

	private void currentuserTemp() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserrec = null;
		try {
			selectCurrentuserrec = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserrec != null) {
			if (selectCurrentuserrec.getCount() > 0) {
				while (selectCurrentuserrec.moveToNext()) {
					currentUserTemp = selectCurrentuserrec.getString(1);
					currentUserPrefix = selectCurrentuserrec.getString(2);
					UserLocCode = selectCurrentuserrec.getString(5);
					String currentUserStRef = selectCurrentuserrec.getString(4);
					UserRouteCode = selectCurrentuserrec.getString(11);
					// Toast.makeText(getApplicationContext(),
					// "currentUserStRef :|"+currentUserStRef, 1).show();
					if (currentUserStRef.equals("0") && TagId.equals(match)) {
						etdmstloadingrefno.setEnabled(false);
					}

				}
			}
		}
		// latestInvoiceNumber();// Get current invoice temp
		selectCurrentuserrec.close();
		mydb.close();
	}

	// Check Current User
	private void currentUserStLoadChk() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserLoad = null;
		try {
			selectCurrentuserLoad = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserLoad != null) {
			if (selectCurrentuserLoad.getCount() > 0) {
				while (selectCurrentuserLoad.moveToNext()) {

					currentUserStLoad = selectCurrentuserLoad.getString(1);
					currentUserPrefixLoad = selectCurrentuserLoad.getString(2);
					// currentUserLocation = selectCurrentuserLoad.getString(3);
				}
			}
		}
		selectCurrentuserLoad.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Check Current Trans Type
	private void stLoadingTransType() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectTransType = null;

		try {
			selectTransType = mydb.query(ITEM_COMPANY_SETTING, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (selectTransType != null) {
			if (selectTransType.getCount() > 0) {
				while (selectTransType.moveToNext()) {
					String cSettingsCode = selectTransType.getString(1);
					String cCharValue = selectTransType.getString(4);
					if (cSettingsCode.equals("DAYNP")) {
						StlTransTypePrefix = cCharValue.trim();
					}
				}
			}
		}
		selectTransType.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	// Check Current Trans Type
	private void checkLatestAdjustmentSerial() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAdjustSerial = null;

		try {
			selectAdjustSerial = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='DAYNP'", null, null, null, null);
		} catch (Exception e) {
		}
		if (selectAdjustSerial != null) {
			if (selectAdjustSerial.getCount() > 0) {
				while (selectAdjustSerial.moveToNext()) {
					String cSettingsCode = selectAdjustSerial.getString(3);
					String nNumVal = selectAdjustSerial.getString(4);
					strLatestAdjustSerial = nNumVal.trim();
					// int numval = Integer
					// .parseInt(strLatestAdjustSerial);
					// int numvalLatest =numval-1;
					// strLatestAdjustSerial = Integer.toString(numvalLatest);

				}
			} else {

				strLatestAdjustSerial = "1";
				try {
					ContentValues newAdjustment = new ContentValues();
					newAdjustment.put("BranchCode", currentUserStLoad);
					newAdjustment.put("RecordId", "1");
					newAdjustment.put("cSettingsCode", "DAYNP");
					newAdjustment.put("nNumVal", strLatestAdjustSerial);
					mydb.insert(INV_COMPANY_BRANCH, null, newAdjustment);

				} catch (Exception e) {
				}
				mydb.close();
			}
		}
		selectAdjustSerial.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Check Current Agent Prefix
	private void stLoadingAgentPrefix() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAgentPreType = null;

		try {
			selectAgentPreType = mydb.query(ITEM_CONTROL, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectAgentPreType != null) {
			if (selectAgentPreType.getCount() > 0) {
				while (selectAgentPreType.moveToNext()) {
					stlAgentPrefixType = selectAgentPreType.getString(18);
				}

			}
		}
		selectAgentPreType.close();
		mydb.close();
	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

	private void createNewAdjustmentAddition() {

		newAdjustmenrRefNoCode = StlTransTypePrefix.trim()
				+ stlAgentPrefixType.trim() + currentUserPrefixLoad;

		try {
			ContentValues addnewAdjustment = new ContentValues();
			addnewAdjustment.put("username", currentUserStLoad);

			try {
				if (strLatestAdjustSerial.length() == 1) {
					String newInvNumberStr = "00000" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else if (strLatestAdjustSerial.length() == 2) {
					String newInvNumberStr = "0000" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else if (strLatestAdjustSerial.length() == 3) {
					String newInvNumberStr = "000" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else if (strLatestAdjustSerial.length() == 4) {
					String newInvNumberStr = "00" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else if (strLatestAdjustSerial.length() == 5) {
					String newInvNumberStr = "0" + strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				} else {
					String newInvNumberStr = strLatestAdjustSerial;
					currentAdjustRefCode = newAdjustmenrRefNoCode.trim() + "/"
							+ newInvNumberStr;
				}
			} catch (Exception e) {
				// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
			}

			addnewAdjustment.put("refSerial", strLatestAdjustSerial);
			addnewAdjustment.put("refCode", currentAdjustRefCode);
			addnewAdjustment.put("currentState", "9");
			addnewAdjustment.put("activeMode", "0");
			addnewAdjustment.put("LocCode", "0");
			addnewAdjustment.put("LocName", "");
			addnewAdjustment.put("TotalAmount", "0.0");
			addnewAdjustment.put("ManuRefNo", "");
			addnewAdjustment.put("AdjustTxnType", "50");

		} catch (Exception e) {
			// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
		}
		etdmstloadingrefno.setText(currentAdjustRefCode);
		etdmstloadingdate = (EditText) findViewById(R.id.etdmstloadingdate);

	}

	private void updateFcompanyBranch() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectUserSerial = null;

		try {
			selectUserSerial = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='DAYNP' AND BranchCode='"
							+ currentUserStLoad + "'", null, null, null, null);
		} catch (Exception e) {
		}
		if (selectUserSerial != null) {
			if (selectUserSerial.getCount() > 0) {
				if (selectUserSerial.moveToLast()) {
					ContentValues updateNewSerial = new ContentValues();
					String serialStId = selectUserSerial.getString(0);
					updateNewSerial.put("nNumVal", strLatestAdjustSerial);
					mydb.update(INV_COMPANY_BRANCH, updateNewSerial,
							"fcombra_id ='" + serialStId + "'", null);
				}
			}
		}
		selectUserSerial.close();
		mydb.close();
	}

	// get current data and time
	private String getCurrentTimeStringCustom() {
		Calendar c = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedDate = df.format(c.getTime());
		return formattedDate;
	}

	private String getCurrentTimeString() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}

	public void DisplayRetailerDetails(View view) {
		Button retailerDet = (Button) view;
		retailerCode = retailerDet.getText().toString();

		String string = retailerCode;
		String[] parts = string.split("/");
		String retailerCode1 = parts[0]; // 004
		String part2 = parts[1]; // 034556
		Log.v("", "retailerCode Status/ -::" + part2 + ":" + part2);

		txtDate = getCurrentTimeString().toString();
		Log.v("", "txtDate Length/ -::" + txtDate);
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		Cursor allrowitemsdesNoneVal = null; // none prd list
		String sWhereCondition = null;
		try {
			sWhereCondition = "TXNDATE='" + txtDate + "'";
			allrowitemsdesNoneVal = mydb.query(DAILY_NONE_PRDCALLS_HEAD, null,
					sWhereCondition, null, null, null, null);
			Log.v("", "allrowitemsdesNoneVal Length/ -::"
					+ allrowitemsdesNoneVal.getCount());
		} catch (Exception e) {
			// handle the exception here
			// for example close the database connections etc..
			Log.v("", "allrowitemsdesNoneVal Length/ -::"
					+ allrowitemsdesNoneVal.getCount());
		}

		// rawitemsdet = DebName + "/" + Status;

		if (part2.equals("V")) {
			Log.v("", "retailerCode Status Stop/ -::" + part2 + ":" + part2);

			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_ProductiveCalls.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("Validate Visit");
			// Setting Dialog Message
			alertDialog
					.setMessage("Cannot Enter a Reason for Visit Customers...");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();

				}
			});
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;

		} else if (allrowitemsdesNoneVal.getCount() == 0) {

			Log.v("",
					"FNonePrd Zero Stop/ -::"
							+ allrowitemsdesNoneVal.getCount());

			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_ProductiveCalls.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("Validate Update");
			// Setting Dialog Message
			alertDialog
					.setMessage("Cannot Enter a Reason Before Update.Please Click Update For Continue...");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();

				}
			});
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		} else {

			Log.v("", "retailerCode PCalls/ retailerCode -::" + retailerCode1
					+ ":" + retailerCode1);
			Intent myIntent = new Intent(view.getContext(),
					DM_NoneProdCall_Reason.class);
			myIntent.putExtra("retailerCode1", retailerCode1);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			finish();
		}

		allrowitemsdesNoneVal.close();
		mydb.close();
	}

	// Auto Increment Number
	public void AutoIncrementRefNo() {
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		Cursor getCurrentRecDaily = null;
		Cursor getCurrentRecFcomp = null;
		Cursor getCurrentRecDailyFDate = null;
		String WhereCondition = null;
		txtDate = getCurrentTimeString().toString();

		try {
			getCurrentRecDaily = mydb.query(DAILY_NONE_PRDCALLS_HEAD, null,
					null, null, null, null, null);
			Log.v("",
					"TagID NONEPRD / TagID -::" + getCurrentRecDaily.getCount()
							+ ":" + getCurrentRecDaily.getCount());
		} catch (Exception e) {
		}

		try {
			WhereCondition = "TXNDATE='" + txtDate + "'";
			getCurrentRecDailyFDate = mydb.query(DAILY_NONE_PRDCALLS_HEAD,
					null, WhereCondition, null, null, null, null);
			Log.v("", "TagID NONEPRDFRDATE / TagID -::"
					+ getCurrentRecDailyFDate.getCount() + ":"
					+ getCurrentRecDailyFDate.getCount());
		} catch (Exception e) {
		}

		try {
			getCurrentRecFcomp = mydb.query(INV_COMPANY_BRANCH, null,
					"cSettingsCode='DAYNP'", null, null, null, null);
			Log.v("",
					"TagID COMBRANCH / TagID -::"
							+ getCurrentRecFcomp.getCount() + ":"
							+ getCurrentRecFcomp.getCount());
		} catch (Exception e) {

		}

		if (getCurrentRecDaily != null) {
			if (getCurrentRecDaily.getCount() > 0) {

				if (getCurrentRecDailyFDate != null) {
					if (getCurrentRecDailyFDate.getCount() > 0) {

						if (getCurrentRecDailyFDate.moveToNext()) {
							TxndateRefno = getCurrentRecDailyFDate.getString(2);
							String RefNo = getCurrentRecDailyFDate.getString(1);

							Log.v("", "RefNo-::" + RefNo + ":" + RefNo);
							Log.v("", "Txndate-::" + TxndateRefno + ":"
									+ TxndateRefno);
							Log.v("", "SystemDate-::" + TxndateRefno + ":"
									+ TxndateRefno);

							String stringRefNo = RefNo;
							String[] parts = stringRefNo.split("/");
							String stringRefNo1 = parts[0]; // 004
							String stringRefNo2 = parts[1]; // 034556
							String Date = etdmstloadingdate.getText()
									.toString();
							Log.v("", "stringRefNo2/ -::" + stringRefNo2 + ":"
									+ stringRefNo2);
							Log.v("", "Date" + Date + ":" + Date);

							if (TxndateRefno.equalsIgnoreCase(txtDate)) {
								invDetLastSequence = Integer
										.parseInt(stringRefNo2);
								Log.v("",
										"invDetLastSequence For Same Date/ -::"
												+ invDetLastSequence + ":"
												+ invDetLastSequence);
								strLatestAdjustSerial = Integer
										.toString(invDetLastSequence);
								createNewAdjustmentAddition();

							}

						}
					} else {
						if (getCurrentRecDaily.moveToLast()) {
							TxndateRefno = getCurrentRecDaily.getString(2);
							String RefNo = getCurrentRecDaily.getString(1);

							Log.v("", "RefNo-::" + RefNo + ":" + RefNo);
							Log.v("", "Txndate-::" + TxndateRefno + ":"
									+ TxndateRefno);
							Log.v("", "SystemDate-::" + TxndateRefno + ":"
									+ TxndateRefno);

							String stringRefNo = RefNo;
							String[] parts = stringRefNo.split("/");
							String stringRefNo1 = parts[0]; // 004
							String stringRefNo2 = parts[1]; // 034556
							String Date = etdmstloadingdate.getText()
									.toString();

							invDetLastSequence = Integer.parseInt(stringRefNo2);
							invDetLastSequence = invDetLastSequence + 1;

							Log.v("", "invDetLastSequence For New Date/ -::"
									+ invDetLastSequence + ":"
									+ invDetLastSequence);
							strLatestAdjustSerial = Integer
									.toString(invDetLastSequence);
							createNewAdjustmentAddition();
							updateFcompanyBranch();
						}
					}

				}
			} else {

				if (getCurrentRecFcomp != null) {
					if (getCurrentRecFcomp.getCount() > 0) {
						if (getCurrentRecFcomp.moveToLast()) {

							String RefNoNum = getCurrentRecFcomp.getString(4);

							int numval = Integer.parseInt(RefNoNum);
							int numvalLatest = Integer.parseInt(RefNoNum); // -1;
							strLatestRef = Integer.toString(numvalLatest);
							Log.v("", "numval / numval 1111-::" + numval + ":"
									+ numval);
							Log.v("", "numvalLatest / numvalLatest1111 -::"
									+ numvalLatest + ":" + numvalLatest);
							Log.v("", "strLatest / strLatest 1111-::"
									+ strLatestRef + ":" + strLatestRef);

							invDetLastSequence = Integer.parseInt(RefNoNum);
							invDetLastSequence = invDetLastSequence + 1;

							Log.v("", "invDetLastSequence/ -::"
									+ invDetLastSequence + ":"
									+ invDetLastSequence);
							strLatestAdjustSerial = Integer
									.toString(invDetLastSequence);
							createNewAdjustmentAddition();
							updateFcompanyBranch();
						}
					}
				}
				// /end if getcurrentrec==0

			}
		}

		getCurrentRecDaily.close();
		getCurrentRecFcomp.close();
		mydb.close();
	}

	public void ValidatingRefNo() {

		if (etdmstloadingrefno.length() == 0) {

			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_ProductiveCalls.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("Validating RefNo Reading");
			// Setting Dialog Message
			alertDialog.setMessage("RefNo Cannot Be Empty...");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}

	}

	// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	// Handling Dialog Box Functions
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_SAVE_STOCK_LOADING:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(
					R.layout.dm_dialog_save_adjustment, null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder
					.setTitle("Stock Adjustment Deduction Saved Successfully..");
			dialogbuilder.setView(dialogview);
			StockLoadingAlert = dialogbuilder.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;
		case DIALOG_CANCEL_STOCK_LOADING:
			LayoutInflater inflaterstl = LayoutInflater.from(this);
			View dialogviewstl = inflaterstl.inflate(
					R.layout.dm_dialog_cancel_invoice, null);

			AlertDialog.Builder dialogbuilderstl = new AlertDialog.Builder(this);
			dialogbuilderstl.setTitle("Cancel Stock Adjustment Deduction...");
			dialogbuilderstl.setView(dialogviewstl);
			StockLoadingAlert = dialogbuilderstl.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;

		case DIALOG_UNDO_STOCK_LOADING:
			LayoutInflater inflateru = LayoutInflater.from(this);
			View dialogviewu = inflateru.inflate(
					R.layout.dm_dialog_undo_invoice, null);

			AlertDialog.Builder dialogbuilderu = new AlertDialog.Builder(this);
			dialogbuilderu
					.setTitle("Undo Current Stock Adjustment Deduction...");
			dialogbuilderu.setView(dialogviewu);
			StockLoadingAlert = dialogbuilderu.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;
		case DIALOG_PRINT_STOCK_LOADING:
			LayoutInflater inflaterp = LayoutInflater.from(this);
			View dialogviewp = inflaterp.inflate(
					R.layout.dm_dialog_print_invoice, null);

			AlertDialog.Builder dialogbuilderp = new AlertDialog.Builder(this);
			dialogbuilderp.setTitle("Printing Configuration Failure...");
			dialogbuilderp.setView(dialogviewp);
			StockLoadingAlert = dialogbuilderp.create();
			StockLoadingAlert.setCanceledOnTouchOutside(false);
			break;
		}

		return StockLoadingAlert;

	}

	// populate Vistdetail LoadList

	protected void RefreshNew() {
		// TODO Auto-generated method stub
		SimpleAdapter adaptertrdes = null;
		ListView lvtypedes = (ListView) findViewById(R.id.dmstockloadingdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "colstloaddes_1", "colstloaddes_2",
				"colstloaddes_3", "colstloaddes_4" };
		int[] totrdes = new int[] { R.id.stloaditemrefdet,
				R.id.stloadcasevalue, R.id.stloadpiecevalue,
				R.id.btnstloaditemrefdet };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		Cursor allrowitemsdes = null; // debtor list
		Cursor allrowitemsdes2 = null; // invoice list
		Cursor allrowitemsdesNone = null; // none prd list
		// Cursor saveStLoadinghedCur = null;

		try {
			String DebcodeStr = "SELECT RD.RouteCode," + "RD.DebCode,"
					+ "FD.DebName," + "FD.OutDis"
					+ " FROM fRouteDet RD,fDebtor FD "
					+ "Where FD.DebCode = RD.DebCode AND RD.RouteCode ='"
					+ UserRouteCode + "'";
			allrowitemsdes = mydb.rawQuery(DebcodeStr, null);

		} catch (Exception e) {
			// handle the exception here
			// for example close the database connections etc..
		}

		int tag = 0;
		String Status = "";
		String DebName = "";
		String DebCode = "";
		String sWhereCondition = null;
		String rawitemsdet = "";
		boolean bInvoiceFound = false;
		boolean bReasonFound = false;

		txtDate = getCurrentTimeString().toString();
		Log.v("", "Date / Date -::" + txtDate + ":" + txtDate);

		if (allrowitemsdes != null) {
			if (allrowitemsdes.getCount() > 0) {
				while (allrowitemsdes.moveToNext()) {
					bInvoiceFound = false;
					bReasonFound = false;
					DebCode = allrowitemsdes.getString(1);
					DebName = allrowitemsdes.getString(2);
					Log.v("", "DebCode******* / DebCode -::" + DebCode + ":"
							+ DebCode);

					try {
						sWhereCondition = "TXNDATE='" + txtDate
								+ "' AND DEBCODE = '" + DebCode + "'";
						allrowitemsdes2 = mydb.query(INV_DETAILS,
								new String[] { "1" }, sWhereCondition, null,
								null, null, null);
						Log.v("", "sWhereCondition1 / sWhereCondition:"
								+ sWhereCondition + ":" + sWhereCondition);
					} catch (Exception e) {
						// handle the exception here
						// for example close the database connections etc..
					}

					if (allrowitemsdes2 != null) {
						if (allrowitemsdes2.getCount() > 0) {
							bInvoiceFound = true;
							Status = "V";
							tag = 1;
						}
					}
					Log.v("", "status / bInvoiceFound:" + bInvoiceFound + ":"
							+ bInvoiceFound);

					if (!bInvoiceFound) {
						try {
							sWhereCondition = "TXNDATE='" + txtDate
									+ "' AND DEBCODE = '" + DebCode
									+ "' AND UPPER(Status) = 'NP'";
							allrowitemsdesNone = mydb.query(
									DAILY_NONE_PRDCALLS_HEAD,
									new String[] { "1" }, sWhereCondition,
									null, null, null, null);
							Log.v("", "sWhereCondition2 / sWhereCondition:"
									+ sWhereCondition + ":" + sWhereCondition);
						} catch (Exception e) {
							// handle the exception here
							// for example close the database connections etc..
						}
						if (allrowitemsdesNone != null) {
							if (allrowitemsdesNone.getCount() > 0) {
								while (allrowitemsdesNone.moveToNext()) {
									bReasonFound = true;
									Status = "NP";
									tag = 1;
								}
							}
						}
					}

					if ((!bInvoiceFound) && (!bReasonFound)) {
						Status = "NV";
						tag = 1;
						rawitemsdet = DebName + "/" + Status;

					}
					rawitemsdet = DebName + "/" + Status;
					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("colstloaddes_1", DebName);
					maptrdes.put("colstloaddes_2", "");
					maptrdes.put("colstloaddes_3", Status);
					maptrdes.put("colstloaddes_4", rawitemsdet);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				adaptertrdes = new SimpleAdapter(this, fillMapstrdes,
						R.layout.dm_daily_loading_list_raw, fromtrdes, totrdes);

				lvtypedes.setAdapter(adaptertrdes);
				final AlertDialog alertDialog = new AlertDialog.Builder(
						DM_ProductiveCalls.this).create();

			}

		}

		if (!allrowitemsdes.isClosed()) {
			allrowitemsdes.close();
		}
		if (!allrowitemsdes2.isClosed()) {
			allrowitemsdes2.close();
		}
		if (allrowitemsdesNone == null) {
			allrowitemsdesNone.close();
		}
		if (!allrowitemsdesNone.isClosed()) {
			allrowitemsdesNone.close();
		}
		if (mydb.isOpen()) {
			mydb.close();
		}
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}
}
